<?php

namespace app\aiv110\controller;

use app\aiv110\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\aiv110\model\Order;
use app\aiv110\model\Store;
use app\aiv110\model\Custom;
use app\aiv110\model\CtmSpecial;
use app\util\Ocr;
use app\aiv110\model\CtmFlow;
use app\aiv110\model\Item;
use app\aiv110\model\ItemToGoods;
use app\aiv110\model\Staff;
use app\aiv110\model\StoreFlow;
use app\aiv110\model\StaffFlow;
use app\aiv110\model\StaffFlowNew;

class SmallstoreController extends CommonController {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 80000  您不是特权用户
         * 80001  您已经开通了小店
         * 80002  您的身份审核失败，请上传真实的身份证件照
         * 80003  请上传身份证
         * 80004  开通失败
         * 80005  该身份证已经开通小店
         * 80006  已为您在美容师端和小程序美容师个人主页开通小店，不支持重复开店
         * 80007  已为您在店铺端和小程序店铺主页开通小店，不支持重复开店
         * 80008
         * 80009
         * 80010
         * 80011
         */
    }
    
    /*
     * 查询用户开通特权的店铺
     * 日期 2020-05-06
     */

    public function ctmSpecialStore() {
        $rule = [
            'ctm_id' => 'require',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $ctm_id = $all['ctm_id'];
        $orderRow = Order::where('ctm_id',$ctm_id)
                ->where('status',2)
                ->where('pay_status',2)
                ->where('type',4)
                ->order('id desc')
                ->field('store_id')
                ->find();
        if($orderRow['store_id']!=0){
            $storeRow = Store::where('id',$orderRow['store_id'])
                    ->field('id,store_name,store_address')
                    ->find();
        }  else {
            $storeRow = [];
        }
        
        return Utils::ajaxReturn(0, '申请成功', $storeRow);
    }

    /*
     * 申请开通小店
     * 日期 2020-05-06
     */

    public function applySmallStore() {
        $rule = [
            'store_id' => 'require',
            'ctm_id' => 'require',
        ];
        $msg = [
            'store_id.require' => '店铺id必须',
            'ctm_id.require' => '用户id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $store_id = $all['store_id'];
        $ctm_id = $all['ctm_id'];
        $idcard1 = input('param.idcard1'); //身份证正面
        $idcard2 = input('param.idcard2'); //身份证反面
        $ctmRow = Custom::where('id',$ctm_id)->field('vip_status,is_smallshop')->find();
        if($ctmRow['vip_status']!= 2){
            return Utils::ajaxReturn(80000, '您不是特权用户', null);
        }
        if($ctmRow['is_smallshop']== 1){
            return Utils::ajaxReturn(80001, '您已经开通了小店', null);
        }
        if (empty($idcard1)) {
            return Utils::ajaxReturn(80003, '请上传身份证', null);
        }
        //查询开通小店邀请人 开通小店的邀请人是根据他开通特权的邀请人 没有邀请人的话是按照选择的店铺算的，找到店铺在custom表里的id
        $orderRow = Order::where('ctm_id',$ctm_id)
                ->where('status',2)
                ->where('pay_status',2)
                ->where('type',4)
                ->order('id desc')
                ->field('store_id,mini_shop_id,is_shop_open')
                ->find();
        if(!empty($orderRow) && $orderRow['mini_shop_id']!=0 && $orderRow['is_shop_open']==1){
            $smallshop_invite_ctmid = $orderRow['mini_shop_id'];
        }  else {
            $smallshop_invite_ctmid = Custom::where('smallshop_type',2)->where('smallshop_otherid',$store_id)->value('id');
        }
        $ocr = new Ocr();
        $data = $ocr->ocrIdcard($idcard1);
        //$data['code'] = 0; //测试不验证
        if($data['code'] == 0){
            $r = json_decode($data['data'],true);
            //$r['num'] = time(); //测试不验证
            if($r['num']){
                $staffRow = Staff::where('idcard_num',$r['num'])->where('staff_on',1)->field('id,staff_is_creator')->find();
                if($staffRow && $staffRow['staff_is_creator']==0){//美容师
                    return Utils::ajaxReturn(80006, '已为您在美容师端和小程序美容师个人主页开通小店，不支持重复开店', null);
                }
                if($staffRow && $staffRow['staff_is_creator']==1){//店铺
                    return Utils::ajaxReturn(80007, '已为您在店铺端和小程序店铺主页开通小店，不支持重复开店', null);
                }
                $customRow = Custom::where('cardnum',$r['num'])->find();
                if($customRow){
                    return Utils::ajaxReturn(80005, '该身份证已经开通小店', null);
                }
            }  else {
                return Utils::ajaxReturn(80002, '您的身份审核失败，请上传真实的身份证件照', null);
            }
            
            $IndexPath = config('appconfig.IndexPath');
            $postFields['modeName'] = 'smallstore';
            $postFields['img'] = $idcard1;
            $img = Utils::curlPost1($IndexPath . 'Public/uploadBase64Img/', $postFields);
            $img = json_decode($img,TRUE);
            $idcard1 = $img['data'];
            
            $IndexPath = config('appconfig.IndexPath');
            $postFields['modeName'] = 'smallstore';
            $postFields['img'] = $idcard2;
            $img2 = Utils::curlPost1($IndexPath . 'Public/uploadBase64Img/', $postFields);
            $img2 = json_decode($img2,TRUE);
            $idcard2 = $img2['data'];
            
            $saveCtm = Custom::where('id',$ctm_id)
                    ->update([
                        'is_smallshop' => 1,
                        'smallshop_storeid' => $store_id,
                        'idcard1' => $idcard1,
                        'idcard2' => $idcard2,
                        'cardnum' => $r['num'],
                        'smallshop_time' => date('Y-m-d H:i:s'),
                        'smallshop_invite_ctmid' => $smallshop_invite_ctmid//开通小店邀请人	
                    ]);
            if($saveCtm){
                return Utils::ajaxReturn(0, '开通成功', null);
            }  else {
                return Utils::ajaxReturn(80004, '开通失败', null);
            }
        }  else {
            return Utils::ajaxReturn(80002, '您的身份审核失败，请上传真实的身份证件照', null);
        }
    }
    
    /*
     * 我的推广订单
     * 日期 2020-05-07
     * 待付款    pay_order_detail 表status=1
     * 交易完成  pay_order_detail 表status=2,3,4
     * 已结算    pay_order_detail 表status=4  and   ai_ctm_flow"用户流水表" 有数据
     * 退款      pay_order_detail 表status=5,6
     * 
     */

    public function smallStoreOrderList() {
        $rule = [
            'ctm_id' => 'require',
            'type' => 'require',
            'status' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'type.require' => '分类必须',
            'status.require' => '状态必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $ctm_id = $all['ctm_id'];
        $type = $all['type'];//1商品订单 2特权订单
        $status = $all['status']; //0全部 1待付款 2交易完成 3已结算=》已取消 4退款
        if($type == 1){
            if($status == 1){
                $where['d.status'] = 1;
                $b = "IF(o.status=1,o.prepay_id IS NOT NULL,1=1)";
            }elseif ($status == 2) {
                $where['d.status'] = ['in','2,3,4'];
                $where['og.is_refund'] = ['notin','1,2'];
                $a = "(SELECT COUNT(`id`) FROM `ai_ctm_flow` WHERE `ctm_id`=" . $ctm_id . " and `pro_type`=9 and `order_id`=d.id) = 0";
                //$where["(SELECT COUNT(`id`) FROM `ai_ctm_flow` WHERE `ctm_id`=" . $ctm_id . " and `pro_type`=9 and `order_id`=og.id)"] = 0;
            }elseif ($status == 3) {
                $where['d.status'] = 0;
                //$where['og.is_refund'] = ['notin','1,2'];
                //$a = "(SELECT COUNT(`id`) FROM `ai_ctm_flow` WHERE `ctm_id`=" . $ctm_id . " and `pro_type`=9 and `order_id`=d.id) = 1";
                
//$where["(SELECT COUNT(`id`) FROM `ai_ctm_flow` WHERE `ctm_id`=" . $ctm_id . " and `pro_type`=9 and `order_id`=og.id)"] = 1;
            }elseif ($status == 4) {
                //$where['d.status'] = ['in','5,6'];
                $where['og.is_refund'] = ['in','1,2'];
            }elseif ($status == 0) {
                $b = "IF(o.status=1,o.prepay_id IS NOT NULL,1=1)";
            }
        }elseif ($type == 2) {
            if($status){
                $where['o.status'] = $status;
            }
        }
        
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        $a = isset($a) ? $a : '';
        $b = isset($b) ? $b: '';
        $where = isset($where) ? $where : [];
        if($type == 1){
            //$where['d.mini_shop_id'] = $ctm_id;
            $list = Db::table('pay_order_detail')->alias('d')
                    ->join(['pay_order' => 'o'], 'o.order_id = d.parent_order_id', 'left')
                    ->join(['pay_order_goods' => 'og'], 'og.pay_order_id = d.id', 'left')
                    ->join(['brand_info' => 'b'], 'b.id = d.brand_id', 'left')
                    ->join('custom c', 'c.id = d.ctm_id', 'left')
                    ->where($where)
                    ->where($a)
                    ->where($b)
                    ->where("d.mini_shop_id=".$ctm_id." OR d.store_id IN (SELECT smallshop_otherid FROM ai_custom WHERE id = ".$ctm_id." AND smallshop_type=2)")
                    ->order('d.add_time desc')
                    ->limit($offset, $perPage)
                    ->field('c.custom_name,c.custom_photo,d.order_id,d.parent_order_id,d.status,d.add_time,d.mini_shop_id,d.ctm_id,b.name,d.id,og.goods_icon,og.name goodsname,og.price,og.goods_detail_name,og.goods_detail_id,og.is_refund,og.number,o.pay_money,o.balance_money')
                    ->select();
            foreach ($list as $k => $v) {
                if($v['status'] == 0 ){//订单状态,0已取消,1待付款,2待发货,3待收货,4已完成6已退款
                    $list[$k]['statusStr'] = '已取消'; 
                }elseif ($v['status'] == 1) {
                    $list[$k]['statusStr'] = '待付款'; 
                }elseif ($v['status'] == 2) {
                    $list[$k]['statusStr'] = '待发货'; 
                }elseif ($v['status'] == 3) {
                    $list[$k]['statusStr'] = '待收货'; 
                }elseif ($v['status'] == 4) {
                    $list[$k]['statusStr'] = '已完成'; 
                }
                if($v['is_refund']==1){
                    $list[$k]['status'] = 5; //退款中
                    $list[$k]['statusStr'] = '退款中'; 
                }
                if($v['is_refund']==2){
                    $list[$k]['status'] = 6; //已退款
                    $list[$k]['statusStr'] = '已退款'; 
                }
                if ($v['status'] == 4) {
                    $ctmFlowRow = CtmFlow::where('ctm_id', $ctm_id)
                            ->where('pro_type', 9)
                            ->where('order_id', $v['id'])
                            ->find();
                    if ($ctmFlowRow) {
                        $list[$k]['status'] = 7; //已结算
                        $list[$k]['statusStr'] = '已结算'; 
                    }
                }
                if($v['ctm_id'] == $v['mini_shop_id']){//自己买自己小店的没有佣金
                    $list[$k]['promoteIncome'] = 0;
                }  else {
                    $leaveFactoryPrice = Db::table('goods_info_detail')->where('id',$v['goods_detail_id'])->value('leaveFactoryPrice');
                    $list[$k]['promoteIncome'] = bcmul(bcsub($v['price'],$leaveFactoryPrice),0.4);
                }
                
            }
            return Utils::ajaxReturn(0, 'success', $list);
        }elseif ($type == 2) {
            $ctmRow = Custom::where('id',$ctm_id)->field('smallshop_type,smallshop_otherid')->find();
            if($ctmRow['smallshop_type'] == 2){//店铺的小店 查store_flow
                $where['o.type'] = 4;
                $where['f.pro_type'] = 4;
                $where['f.store_id'] = $ctmRow['smallshop_otherid'];
                $list = StoreFlow::alias('f')
                        ->join('order o','o.id = f.order_id','left')
                        ->join('custom c','c.id = o.ctm_id','left')
                        ->where($where)
                        ->order('o.add_time desc')
                        ->limit($offset, $perPage)
                        ->field('c.custom_name,c.custom_photo,o.ord_num,o.add_time,o.pay_money,o.balance_money,o.status')
                        ->select();
            }  else {
                $where['o.mini_shop_id'] = $ctm_id;
                $where['o.is_shop_open'] = 1;
                $where['o.type'] = 4;
                $list = Order::alias('o')
                        ->join('custom c', 'c.id = o.ctm_id', 'left')
                        ->where($where)
                        ->order('o.add_time desc')
                        ->limit($offset, $perPage)
                        ->field('c.custom_name,c.custom_photo,o.ord_num,o.add_time,o.pay_money,o.balance_money,o.status')
                        ->select();
            }
            
            foreach ($list as $k => $v){
                $list[$k]['goods_icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/special.png';
                $list[$k]['goodsname'] = '99特权';
                $list[$k]['promoteIncome'] = 9900;
                if($v['status'] == 0 ){//订单状态,0已取消 1待支付 2已完成=已支付 3已退款
                    $list[$k]['statusStr'] = '已取消'; 
                }elseif ($v['status'] == 1) {
                    $list[$k]['statusStr'] = '待付款'; 
                }elseif ($v['status'] == 2) {
                    $list[$k]['statusStr'] = '已完成'; 
                }elseif ($v['status'] == 3) {
                    $list[$k]['statusStr'] = '已退款'; 
                }
            }
            return Utils::ajaxReturn(0, 'success', $list);
        }
    }
    
    /*
     * i美优优首页（体验项目家居装）
     * author xfwed 
     * date 2020.08.07
     */

    public function index() {
        $rule = [
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        $a = isset($a) ? $a : '';
        
        $where['i.is_del'] = 1;
//        $list = Item::where($where)
//                ->order('sell_count desc')
//                ->limit($offset, $perPage)
//                ->field('id,item_name,item_price,special_money,item_img,sell_count')
//                ->select();
        $list = ItemToGoods::alias('g')
                ->join('item i','i.id = g.item_id')
                ->where($where)
                ->order('i.sell_count desc')
                ->limit($offset, $perPage)
                ->group('g.item_id')
                ->field('i.id,i.item_name,i.item_price,i.special_money,i.item_img,i.sell_count')
                ->select();

        return Utils::ajaxReturn(0, 'success', $list);
        
    }
    
    /*
     * i美优优（体验项目家居装商品）
     * author xfwed 
     * date 2020.08.11
     */

    public function imGoods() {
        $rule = [
            'item_id' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'item_id.require' => '项目id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $item_id = $all['item_id'];
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        $a = isset($a) ? $a : '';
        
        $where['i.item_id'] = $item_id;
        $where['g.valid'] = 1;
        $where['g.verifyStatus'] = 2;
        $where['g.is_dis'] = 2;
        $where['g.is_smallshopsell'] = 1;
      
        $list = ItemToGoods::alias('i')
                ->join(['goods_info'=>'g'],'g.id = i.goods_info_id','left')
                ->join(['goods_info_detail'=>'d'],'d.goodsId = g.id','left')
                ->where($where)
                ->order('g.sell_count desc')
                ->group('i.goods_info_id')
                ->limit($offset, $perPage)
                ->field('g.id,g.name,g.icon,g.sell_count,d.oriPrice,d.price,d.leaveFactoryPrice,d.deduct_money')
                ->select();
        foreach ($list as $k => $v){
            $list[$k]['mybuy'] = bcmul($v['price'],0.12);
            $a = $v['price']*0.88;
            $a = bcsub($a,$v['leaveFactoryPrice']);
            $a = bcsub($a,$v['deduct_money']);
            $list[$k]['sharebuy'] = bcmul($a,0.4);
        }

        return Utils::ajaxReturn(0, 'success', $list);
        
    }
    
    /*
     * 我的伙伴
     * author xfwed 
     * date 2020.09.02
     */

    public function myCully() {
        $rule = [
            'ctm_id' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $ctm_id = $all['ctm_id'];
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        
        $where['smallshop_invite_ctmid'] = $ctm_id;
        $where['is_smallshop'] = 1;
        
        $list = Custom::where($where)
                ->order('smallshop_time desc')
                ->field('id,custom_name,custom_photo,smallshop_time')
                ->limit($offset, $perPage)
                ->select();
        $data['num'] = Custom::where($where)->count();
        foreach ($list as $k => $v){
            $id = $v['id'];
            $specialMoney = CtmFlow::alias('f')
                    ->join('order o','o.id = f.order_id','left')
                    ->where('f.pro_type','=',8)
                    ->where('f.ctm_id',$ctm_id)
                    ->where('o.ctm_id',$id)
                    ->sum('f.money');
            $goodsMoney = CtmFlow::alias('f')
                    ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                    ->where('f.pro_type','=',9)
                    ->where('f.ctm_id',$ctm_id)
                    ->where('o.ctm_id',$id)
                    ->sum('f.money');        
            $list[$k]['money'] = $specialMoney + $goodsMoney;
        }
        $data['list'] = $list;
        return Utils::ajaxReturn(0, 'success', $data);
        
    }
    /*
     * 伙伴详情
     * author xfwed 
     * date 2020.09.02
     */

    public function myCullyInfo() {
        $rule = [
            'ctm_id' => 'require',//邀请者id
            'id' => 'require',//被邀请者id
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctm_id.require' => '邀请者id必须',
            'id.require' => '被邀请者id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $ctm_id = $all['ctm_id'];
        $id = $all['id'];
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        
        $ctmRow = Custom::where('id',$id)->field('id,custom_name,custom_photo,smallshop_time')->find();

        $specialMoney = CtmFlow::alias('f')
                ->join('order o','o.id = f.order_id','left')
                ->where('f.pro_type','=',8)
                ->where('f.ctm_id',$ctm_id)
                ->where('o.ctm_id',$id)
                ->sum('f.money');
        $goodsMoney = CtmFlow::alias('f')
                ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                ->where('f.pro_type','=',9)
                ->where('f.ctm_id',$ctm_id)
                ->where('o.ctm_id',$id)
                ->sum('f.money');        
        $ctmRow['money'] = $specialMoney + $goodsMoney;    
        $data['ctmRow'] = $ctmRow;
        $matSql = CtmFlow::alias('f')
                ->join('order o','o.id = f.order_id','left')
                ->where('f.pro_type','=',8)
                ->where('f.ctm_id',$ctm_id)
                ->where('o.ctm_id',$id)
                ->field('f.money,f.pro_type,o.pay_money,o.balance_money,o.ord_num,o.add_time,"" name,"" goods_icon')
                ->buildSql();
        
        $list = CtmFlow::alias('f')
                ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                ->join(['pay_order_goods'=>'d'],'d.pay_order_id = o.id','left')
                ->where('f.pro_type','=',9)
                ->where('f.ctm_id',$ctm_id)
                ->where('o.ctm_id',$id)
                ->field('f.money,f.pro_type,o.pay_money,"" balance_money,o.order_id ord_num,o.add_time,d.name,d.goods_icon')
                ->limit($offset, $perPage)
                ->union($matSql, true)
                ->select(); 
        foreach ($list as $k => $v){
            if(empty($v['balance_money'])){
                $list[$k]['balance_money'] = 0;
            }
           if($v['pro_type'] == 8){
               $list[$k]['name'] = "99特权卡";
               $list[$k]['goods_icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/special.png';
           } 
        }
        $data['list'] = $list;
        return Utils::ajaxReturn(0, 'success', $data);
        
    }
    
    
    /*
     * 我的伙伴(修改后的)
     * author xfwed 
     * date 2020.09.26
     */

    public function newMyCully() {
        $rule = [
            'ctm_id' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctm_id.require' => '用户id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $ctm_id = $all['ctm_id'];
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        
        //查询用户信息 确定用户身份
        $ctmRow = Custom::where('id',$ctm_id)->field('smallshop_type,smallshop_otherid')->find();
        $smallshop_type = $ctmRow['smallshop_type'];//小店身份 0.默认用户 1.美容师小店 2.店铺小店
        if($smallshop_type == 0){
            $where['o.mini_shop_id'] = $ctm_id;
            $where['o.is_shop_open'] = 1;
            $where['o.type'] = 4;
            $where['o.status'] = 2;
            $list = Order::alias('o')
                    ->join('custom c','c.id = o.ctm_id','left')
                    ->where($where)
                    ->field('c.id,c.custom_name,c.custom_photo,o.pay_time special_time')
                    ->limit($offset, $perPage)
                    ->group('o.ctm_id')
                    ->order('o.id desc')
                    ->select();
            $num = Order::alias('o')
                    ->join('custom c','c.id = o.ctm_id','left')
                    ->where($where)
                    ->group('o.ctm_id')
                    ->order('o.id desc')
                    ->count();
            foreach ($list as $k => $v){
                $id = $v['id'];
                $specialMoney = CtmFlow::alias('f')
                        ->join('order o','o.id = f.order_id','left')
                        ->where('f.pro_type','=',8)
                        ->where('f.ctm_id',$ctm_id)
                        ->where('o.ctm_id',$id)
                        ->sum('f.money');
                $goodsMoney = CtmFlow::alias('f')
                        ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                        ->where('f.pro_type','=',9)
                        ->where('f.ctm_id',$ctm_id)
                        ->where('o.ctm_id',$id)
                        ->sum('f.money');        
                $list[$k]['money'] = $specialMoney + $goodsMoney;
            }
        }elseif ($smallshop_type == 1) {
            $staff_id = $ctmRow['smallshop_otherid'];
            $where['o.staff_id'] = $staff_id;
            $where['o.type'] = 4;
            $where['o.status'] = 2;
            $list = Order::alias('o')
                    ->join('custom c','c.id = o.ctm_id','left')
                    ->where($where)
                    ->field('c.id,c.custom_name,c.custom_photo,o.pay_time special_time')
                    ->limit($offset, $perPage)
                    ->group('o.ctm_id')
                    ->order('o.id desc')
                    ->select();
            $num = Order::alias('o')
                    ->join('custom c','c.id = o.ctm_id','left')
                    ->where($where)
                    ->group('o.ctm_id')
                    ->order('o.id desc')
                    ->count();
            foreach ($list as $k => $v){
                $id = $v['id'];
                $specialMoney = StaffFlowNew::alias('f')
                        ->join('order o','o.id = f.order_id','left')
                        ->where('f.pro_type','=',4)
                        ->where('f.staff_id',$staff_id)
                        ->where('o.ctm_id',$id)
                        ->where('f.status',2)
                        ->sum('f.money');
                $goodsMoney = StaffFlowNew::alias('f')
                        ->join(['pay_order_goods' => 'g'],'g.id = f.order_id','left')
                        ->join(['pay_order_detail'=>'o'],'o.id = g.pay_order_id','left')
                        ->where('f.pro_type','in','6,7')
                        ->where('f.staff_id',$staff_id)
                        ->where('o.ctm_id',$id)
                        ->where('f.status',2)
                        ->sum('f.money');        
                $list[$k]['money'] = $specialMoney + $goodsMoney;
            }
        }elseif ($smallshop_type == 2) {
            $store_id = $ctmRow['smallshop_otherid'];
            $where['o.store_id'] = $store_id;
            $where['o.type'] = 4;
            $where['o.status'] = 2;
            $list = Order::alias('o')
                    ->join('custom c','c.id = o.ctm_id','left')
                    ->where($where)
                    ->field('c.id,c.custom_name,c.custom_photo,o.pay_time special_time')
                    ->limit($offset, $perPage)
                    ->group('o.ctm_id')
                    ->order('o.id desc')
                    ->select();
            $num = Order::alias('o')
                    ->join('custom c','c.id = o.ctm_id','left')
                    ->where($where)
                    ->group('o.ctm_id')
                    ->order('o.id desc')
                    ->count();
            foreach ($list as $k => $v){
                $id = $v['id'];
                $specialMoney = StoreFlow::alias('f')
                        ->join('order o','o.id = f.order_id','left')
                        ->where('f.pro_type','=',4)
                        ->where('f.store_id',$store_id)
                        ->where('o.ctm_id',$id)
                        ->sum('f.money');
                $goodsMoney = StoreFlow::alias('f')
                        ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                        ->where('f.pro_type','=',7)
                        ->where('f.store_id',$store_id)
                        ->where('o.ctm_id',$id)
                        ->sum('f.money');        
                $list[$k]['money'] = $specialMoney + $goodsMoney;
            }
        }
        $data['num'] = $num;
        $data['list'] = $list;
        return Utils::ajaxReturn(0, 'success', $data);
        
    }
    /*
     * 伙伴详情(修改后的)
     * author xfwed 
     * date 2020.09.26
     */

    public function newMyCullyInfo() {
        $rule = [
            'ctm_id' => 'require',//邀请者id
            'id' => 'require',//被邀请者id
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctm_id.require' => '邀请者id必须',
            'id.require' => '被邀请者id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $ctm_id = $all['ctm_id'];
        $id = $all['id'];
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        //被邀请者信息
        $ctmRow = Custom::where('id',$id)->field('id,custom_name,custom_photo,smallshop_time')->find();
        
        //邀请者信息  查询用户信息 确定用户身份
        $ctmRow2 = Custom::where('id',$ctm_id)->field('smallshop_type,smallshop_otherid')->find();
        $smallshop_type = $ctmRow2['smallshop_type'];//小店身份 0.默认用户 1.美容师小店 2.店铺小店
        if($smallshop_type == 0){
            $specialMoney = CtmFlow::alias('f')
                ->join('order o','o.id = f.order_id','left')
                ->where('f.pro_type','=',8)
                ->where('f.ctm_id',$ctm_id)
                ->where('o.ctm_id',$id)
                ->sum('f.money');
            $goodsMoney = CtmFlow::alias('f')
                    ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                    ->where('f.pro_type','=',9)
                    ->where('f.ctm_id',$ctm_id)
                    ->where('o.ctm_id',$id)
                    ->sum('f.money');        
            $ctmRow['money'] = $specialMoney + $goodsMoney;    
            $data['ctmRow'] = $ctmRow;
            $matSql = CtmFlow::alias('f')
                    ->join('order o','o.id = f.order_id','left')
                    ->where('f.pro_type','=',8)
                    ->where('f.ctm_id',$ctm_id)
                    ->where('o.ctm_id',$id)
                    ->field('f.money,f.pro_type,o.pay_money,o.balance_money,o.ord_num,o.add_time,"" name,"" goods_icon')
                    ->buildSql();

            $list = CtmFlow::alias('f')
                    ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                    ->join(['pay_order_goods'=>'d'],'d.pay_order_id = o.id','left')
                    ->where('f.pro_type','=',9)
                    ->where('f.ctm_id',$ctm_id)
                    ->where('o.ctm_id',$id)
                    ->field('f.money,f.pro_type,o.pay_money,"" balance_money,o.order_id ord_num,o.add_time,d.name,d.goods_icon')
                    ->limit($offset, $perPage)
                    ->union($matSql, true)
                    ->select(); 
            foreach ($list as $k => $v){
                if(empty($v['balance_money'])){
                    $list[$k]['balance_money'] = 0;
                }
               if($v['pro_type'] == 8){
                   $list[$k]['name'] = "99特权卡";
                   $list[$k]['goods_icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/special.png';
               } 
            }
        }elseif ($smallshop_type == 1) {
            $staff_id = $ctmRow2['smallshop_otherid'];
            $specialMoney = StaffFlowNew::alias('f')
                ->join('order o','o.id = f.order_id','left')
                ->where('f.pro_type','=',4)
                ->where('f.staff_id',$staff_id)
                ->where('o.ctm_id',$id)
                ->where('f.status',2)
                ->sum('f.money');
            $goodsMoney = StaffFlowNew::alias('f')
                    ->join(['pay_order_goods' => 'g'],'g.id = f.order_id','left')
                    ->join(['pay_order_detail'=>'o'],'o.id = g.pay_order_id','left')
                    ->where('f.pro_type','in','6,7')
                    ->where('f.staff_id',$staff_id)
                    ->where('o.ctm_id',$id)
                    ->where('f.status',2)
                    ->sum('f.money');        
            $ctmRow['money'] = $specialMoney + $goodsMoney;    
            $data['ctmRow'] = $ctmRow;
            $matSql = StaffFlowNew::alias('f')
                    ->join('order o','o.id = f.order_id','left')
                    ->where('f.pro_type','=',4)
                    ->where('f.staff_id',$staff_id)
                    ->where('o.ctm_id',$id)
                    ->where('f.status',2)
                    ->field('f.money,f.pro_type,o.pay_money,o.balance_money,o.ord_num,o.add_time,"" name,"" goods_icon')
                    ->buildSql();

            $list = StaffFlowNew::alias('f')
                    ->join(['pay_order_goods'=>'d'],'d.id = f.order_id','left')
                    ->join(['pay_order_detail'=>'o'],'o.id = d.pay_order_id','left')
                    ->where('f.pro_type','=',7)
                    ->where('f.staff_id',$staff_id)
                    ->where('o.ctm_id',$id)
                    ->where('f.status',2)
                    ->field('f.money,f.pro_type,o.pay_money,"" balance_money,o.order_id ord_num,o.add_time,d.name,d.goods_icon')
                    ->limit($offset, $perPage)
                    ->union($matSql, true)
                    ->select(); 
            foreach ($list as $k => $v){
                if(empty($v['balance_money'])){
                    $list[$k]['balance_money'] = 0;
                }
               if($v['pro_type'] == 4){
                   $list[$k]['name'] = "99特权卡";
                   $list[$k]['goods_icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/special.png';
               } 
            }
        }elseif ($smallshop_type == 2) {
            $store_id = $ctmRow2['smallshop_otherid'];
            $specialMoney = StoreFlow::alias('f')
                ->join('order o','o.id = f.order_id','left')
                ->where('f.pro_type','=',4)
                ->where('f.store_id',$store_id)
                ->where('o.ctm_id',$id)
                ->sum('f.money');
            $goodsMoney = StoreFlow::alias('f')
                    ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                    ->where('f.pro_type','=',7)
                    ->where('f.store_id',$store_id)
                    ->where('o.ctm_id',$id)
                    ->sum('f.money');        
            $ctmRow['money'] = $specialMoney + $goodsMoney;    
            $data['ctmRow'] = $ctmRow;
            $matSql = StoreFlow::alias('f')
                    ->join('order o','o.id = f.order_id','left')
                    ->where('f.pro_type','=',4)
                    ->where('f.store_id',$store_id)
                    ->where('o.ctm_id',$id)
                    ->field('f.money,f.pro_type,o.pay_money,o.balance_money,o.ord_num,o.add_time,"" name,"" goods_icon')
                    ->buildSql();

            $list = StoreFlow::alias('f')
                    ->join(['pay_order_detail'=>'o'],'o.id = f.order_id','left')
                    ->join(['pay_order_goods'=>'d'],'d.pay_order_id = o.id','left')
                    ->where('f.pro_type','=',7)
                    ->where('f.store_id',$store_id)
                    ->where('o.ctm_id',$id)
                    ->field('f.money,f.pro_type,o.pay_money,"" balance_money,o.order_id ord_num,o.add_time,d.name,d.goods_icon')
                    ->limit($offset, $perPage)
                    ->union($matSql, true)
                    ->select(); 
            foreach ($list as $k => $v){
                if(empty($v['balance_money'])){
                    $list[$k]['balance_money'] = 0;
                }
               if($v['pro_type'] == 4){
                   $list[$k]['name'] = "99特权卡";
                   $list[$k]['goods_icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/special.png';
               } 
            }
        }

        $data['list'] = $list;
        return Utils::ajaxReturn(0, 'success', $data);
        
    }
}
